import axios from 'axios';

export const instance = axios.create();

instance.defautls = {
  timeout: 10000,
  withCredentials: true,
  headers: {
    'content-type': 'application/json',
  },
};

// 全局配置
instance.interceptors.request.use(config => {
  return config;
});
/**
 * 默认响应拦截
 * @param  {object} response 响应内容
 * @return {}
 */
instance.interceptors.response.use(response => {
  switch (response.status) {
    case 200: // get - ok
    case 201: // post/put/patch - created
    case 202: // * - accepted [async task]
    case 204: // delete - no content
    case 422: // post/put/patch - unprocessable entity
      return response.data;
    default:
      return response;
  }
});

//
export function insertRequestInterceptors(interceptors) {
  const req = instance.interceptors.request;
  if (typeof interceptors === 'function') {
    req.use(interceptors);
  } else if (interceptors instanceof Array && interceptors.length) {
    interceptors.forEach(item => {
      if (typeof item === 'function') {
        req.use(item);
      }
    });
  }
}

//
export function insertResponseInterceptors(interceptors) {
  const resp = instance.interceptors.response;
  if (typeof interceptors === 'function') {
    resp.use(interceptors);
  } else if (interceptors instanceof Array && interceptors.length) {
    interceptors.forEach(item => {
      if (typeof item === 'function') {
        resp.use(item);
      }
    });
  }
}

/**
 * 公共请求
 * @param  {string} method 请求方法
 * @param  {string} url    请求地址
 * @param  {object} params  请求参数
 * @return {object}
 */
function request(method, url, params = {}, options = {}) {
  const { ignoreGlobalParams, baseURL, headers } = options;
  const conf = {
    data: {},
    ...instance.defautls,
    url,
    method,
  };

  baseURL && (conf.baseURL = baseURL);
  headers && (conf.headers = { ...conf.headers, ...headers });

  const globalParams = ignoreGlobalParams ? {} : getGlobalParams();

  // 合并参数
  if (method == 'get') {
    conf.params = { ...globalParams, ...params };
  } else {
    conf.data = { ...globalParams, ...params };
  }

  return Promise.resolve(instance(conf)).catch(e => {
    console.err(e);
    //在被跨域或者网络断开的情况下，没有response拦截器不会执行
    // return Promise.resolve(e);
    throw e;
  });
}

export function method(method, url) {
  return (data, options) => request(method, url, data, options);
}

// 创建请求方法
export const get = url => method('get', url);
export const post = url => method('post', url);

//设置默认
export const setOpts = opts => {
  instance.defautls = {
    ...instance.defautls,
    ...opts,
  };
};

let globalParamsMaker = null;
// 全局参数
function getGlobalParams() {
  const gParams = (globalParamsMaker && globalParamsMaker()) || {};
  return {
    ...gParams,
  };
}

// 设置全局参数
export function setGlobalParamsMaker(fn) {
  if (typeof fn === 'function') globalParamsMaker = fn;
}
